package com.example.core.utils;

import cn.hutool.json.JSONObject;
import lombok.Data;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Data
public class Result {

    public static final int SUCCESS = 20000;

    public static final int NOT_FOUND = 404;

    public static final int NO_AUTH = 50008;

    public static final int NO_LOGIN = 50014;

    public static final int ERROR = 500;

    private int code;

    private Object data;

    /***
     *
     * 操作成功
     * @return
     */
    public static Result success() {
        Result result = new Result();
        result.setCode(SUCCESS);
        return result;
    }

    /****
     *
     * 操作成功
     * @param data
     * @return
     */
    public static Result success(Object data) {
        Result result = new Result();
        result.setCode(SUCCESS);
        result.setData(data);
        return result;
    }

    /****
     * 操作失败
     * @return
     */
    public static Result error() {
        Result result = new Result();
        result.setCode(ERROR);
        return result;
    }

    /****
     * 操作失败
     * @param data
     * @return
     */
    public static Result error(Object data) {
        Result result = new Result();
        result.setCode(ERROR);
        result.setData(data);
        return result;
    }

    /****
     *
     * 没有权限
     * @return
     */
    public static Result noAuth() {
        Result result = new Result();
        result.setCode(NO_AUTH);
        result.setData("您没有访问权限");
        return result;
    }

    /****
     * 没有权限并返回
     * @param response
     * @return
     */
    public static void noAuth(HttpServletResponse response) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", NO_AUTH);
        jsonObject.put("data", "您没有访问权限");
        printWriter.write(jsonObject.toJSONString(0));
        printWriter.flush();
        printWriter.close();
    }


    /****
     * 用户还未登录
     * @param response
     * @return
     */
    public static void noLogin(ServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", NO_LOGIN);
        jsonObject.put("data", "您还未登录或者登陆过期，请重新您登录.");
        printWriter.write(jsonObject.toJSONString(0));
        printWriter.flush();
        printWriter.close();
    }
}

